<?php

namespace app\index\service;

use app\common\model\LawCase;
use app\common\model\Trade;
use app\index\dao\TradeDao;
use app\index\model\UM as UM;
use app\index\traits\TradeShareEstimateTrait;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Request;

/**
 * 案源订单
 * Class TradeLawCaseService
 * @package app\index\service
 */
class TradeLawCaseService implements TradableInterface
{
    // dao
    private TradeDao $tradeDao;

    public function __construct(TradeDao $tradeDao)
    {
        $this->tradeDao = $tradeDao;
    }

    /**
     * 新增
     * @param UM $user
     * @param array $params
     * @return  \app\common\model\Trade
     * @deprecated
     */
    public function add(UM $user, array $params): Trade
    {
        // 补齐参数，创建Trade
        $tradeType = TRADE_LAS_CASE;
        $tradeConfig = Config::get("trade.trades.$tradeType", []);
        $tradeTypeClass = $tradeConfig['className'] ?? '';

        $lawCaseId = $params['lawCaseId'] ?? null;
        $num = $params['num'] ?? 1;

        // 渠道链路
        ['pf' => $pf, 'chain' => $chain, 'promotionGroupId' => $promotionGroupId] = getChainParams();

        if (!is_numeric($num) || $num <= 0) {
            throw new ValidateException('请选择正确的数量');
        }

        // 案源
        $lawCase = LawCase::where('id', $lawCaseId)
            ->find();
        if (!$lawCase) {
            throw new ValidateException('该案源不存在，或已被删除');
        }
        if ($lawCase->isPublish != 1) {
            throw new ValidateException('该案源不能购买');
        }
        if ($lawCase->publishTime > time()) {
            throw new ValidateException('该案源还未开始抢购');
        }
        if ($lawCase->surplus < $num) {
            if ($lawCase->surplus == 0) {
                throw new ValidateException('该案源已售罄');
            }
            throw new ValidateException('剩余可购买次数不足');
        }

        $describe = $tradeConfig['name'];

        $showMoney = bcmul($lawCase->price, $num, 2);
        $totalMoney = bcmul($lawCase->price, $num, 2);
        $payMoney = $totalMoney;
        $settleStatus = Trade::UNSETTLED;

        if($payMoney < 0.01){
            throw new ValidateException('订单价格应该大于0');
        }


        $tradeParams = [
            'memberId' => $user->id,
            'orderNoPre' => 'LC',
            'describe' => $describe,
            'tradeType' => $tradeType,
            'tradeTypeClass' => $tradeTypeClass,
            'lawCaseId' => $lawCase->id,
            'showMoney' => $showMoney,
            'totalMoney' => $totalMoney,
            'payMoney' => $payMoney,
            'payStatus' => Trade::UNPAID,
            'payExpTime' => time() + 300,
            'settleStatus' => $settleStatus,
            'num' => $num,
            'pf' => $pf,
            'chain' => $chain,
            'promotionGroupId' => $promotionGroupId,
            'attach' => [
                'attach' => '',
            ],
        ];

        $record = $this->tradeDao->insertTrade($tradeParams);

        // 触发订单创建事件
        event('TradeCreated', $record);

        // 下单时触发案源数量变化事件
        event('LawCaseNumUpdated', $lawCase);

        return $record;
    }

    // 完成订单
    public function completionTrade(Trade $trade)
    {

        $time = time();
        $trade->startTime = $time;
        $trade->save();

        // 触发订单完成事件
        event('TradeEnded', $trade);
    }

    // 完成退款，收回服务
    public function completionRefundTrade(Trade $trade)
    {

        // 触发案源数量变化事件
        $lawCase = LawCase::where('id', $trade->lawCaseId)->find();
        if ($lawCase) {
            event('LawCaseNumUpdated', $lawCase);
        }

    }

    public function canceledTrade(Trade $trade)
    {
        return;
    }
}
